package com.lmt.service.impl;

import com.lmt.base.BaseService;
import com.lmt.base.ResultData;
import com.lmt.entity.ResourceTemp;
import com.lmt.entity.search.ResourceTempSearch;
import com.lmt.repository.ResourceTempRepository;
import com.lmt.service.ResourceTempService;
import com.lmt.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * Date 2018/07/17
 *
 * @author MT-Lin
 */
@Service("ResourceTempServiceImpl")
public class ResourceTempServiceImpl extends BaseService implements ResourceTempService {

	private final ResourceTempRepository resourceTempRepository;

	@Autowired
	public ResourceTempServiceImpl(ResourceTempRepository resourceTempRepository) {
		this.resourceTempRepository = resourceTempRepository;
	}

	@Override
	public ResultData save(ResourceTemp resourceTemp) {
		ResourceTemp exist = this.resourceTempRepository.findByMd5(resourceTemp.getMd5());
		if (null != exist) {
			return ResultUtil.newFail("该文件已存在");
		}
		this.resourceTempRepository.save(resourceTemp);
		if (null == resourceTemp.getId()) {
			return ResultUtil.newFail("资源信息保存失败");
		}
		return ResultUtil.newSuccess("资源上传成功，请等待审核", resourceTemp.getId());
	}

	@Override
	public ResultData search(ResourceTempSearch resourceTempSearch) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT rt.id, rt.designation, rt.description, ");
		sql.append("rt.resource_size AS resourceSize, ");
		sql.append("rt.gmt_create AS gmtCreate, ");
		sql.append("rt.resource_id AS resourceId, ");
		sql.append("ui.user_name AS author, ");
		sql.append("(SELECT c.designation FROM classify AS c WHERE c.id = rt.classify_id) ");
		sql.append("AS classify, ");
		sql.append("(SELECT dd.designation FROM digital_dictionary AS dd WHERE dd.code = rt.resource_type) ");
		sql.append("AS resourceType, ");
		sql.append("(SELECT dd.designation FROM digital_dictionary AS dd WHERE dd.code = a.operation) ");
		sql.append("AS operation, ");
		sql.append("(SELECT dd.code FROM digital_dictionary AS dd WHERE dd.code = a.operation) ");
		sql.append("AS operationCode ");
		sql.append("FROM resource_temp AS rt, audit AS a, user_info AS ui ");
		sql.append("WHERE rt.id = a.obj_id ");
		sql.append("AND a.status = '005003' ");
		sql.append("AND ui.id = rt.author_id ");
		if (!StringUtils.isEmpty(resourceTempSearch.getKeyword())) {
			sql.append("AND (ui.user_name LIKE ? OR rt.designation LIKE ? OR rt.description LIKE ? ) ");
			resourceTempSearch.setParamsCount(3);
		}
		Map result = this.paginationSearch(sql, resourceTempSearch);
		return ResultUtil.newSuccess("查询待审核资源成功", result);
	}

	@Override
	public ResourceTemp findOneById(String resourceTempId) {
		return this.resourceTempRepository.findById(resourceTempId).orElse(null);
	}

	@Override
	public int getUploadNum(String authorId) {
		return this.resourceTempRepository.countByAuthorId(authorId);
	}
}
